// pages/detail/detail.js

const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id : 0,
    orderInfo:{},
    array: ['不限', '1 人', '2 人', '3 人', '4 人', '5 人', '6 人'],
    apiUrl: '',
    imageList : [],
    imagePath: '',
    toPlay: '',
    isPlay: false,
    send_type : 1,
    desc_count : 0,
    recording: "正在 录音",
    select_to_user : false,
    toNote : true,
    description : '',
    description_voice : '',
    upload_images: [],
    is_open : false,
    send_user : '',
    message_list : []  // 留言列表
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    var that = this;
    var id = options.id;

    // 设置全局图片路径
    this.setData({
      imagePath: app.globalData.imagePath,
      id: id,
      apiUrl: app.globalData.apiUrl,
      staticApiUrl: app.globalData.staticApiUrl,
      send_image: app.globalData.imagePath + '/send_voice.png',
      recording_image: app.globalData.imagePath + "/luyin_point.png",
    });

    this.getOrderInfo();

    this.getMessage();

    // 初始化录音
    app.initRecorderManager();
    // 音频自然播放结束事件
    app.data.innerAudioContext.onEnded((res) => {
      that.setData({
        toPlay: ''
      });
    });

    app.data.recorderManager.onStart(function () {
      speaking.call(that);
      recordImageflash.call(that);
      that.setData({
        isSpeaking: true,
        voice_button_msg: "松开 结束",
        record_status: 1
      })
    });

    app.data.recorderManager.onStop(function (res) {
      that.setData({
        description_voice: res.tempFilePath,
        record_status: 2
      })
      that.tip("录音完成！")
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (e) {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // 如果正在播放，跳转页面是停止播放
    if (this.data.isPlay) {
      app.data.innerAudioContext.stop();

      this.setData({
        toPlay: ''
      });
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // 如果正在播放，跳转页面是停止播放
    if (this.data.isPlay) {
      app.data.innerAudioContext.stop();

      this.setData({
        toPlay: ''
      });
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getMessage();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },

  getOrderInfo: function () {
    wx.showLoading({
      title: '加载中',
    });

    var that = this;
    wx.request({
      url: app.globalData.apiUrl + 'index/info',
      header: {
        'content-type': 'application/json',
        "Cookie": "PHPSESSID=" + wx.getStorageSync('sessionID')
      },
      data: {
        id: that.data.id
      },
      success: function (res) {
        if (res.data.code == 10000) {
          that.setData({
            orderInfo: res.data.message,
            imageList: res.data.message.image_list
          });
        } else {
          that.data.orderInfo = {};
        }
        wx.hideLoading();
      },
      fail : function() {
        wx.hideLoading();
      }
    })
  },
  /**
   * 跳转到参与页面
   */
  toJoin : function(e) {
    
    app.checkAuthUserInfo();
    app.formIdSubmit(e);

    var id = e.currentTarget.id
    wx.navigateTo({
      url: '/pages/toJoin/toJoin?id=' + id
    })  
  },
  /**
   * 图片展示
   */
  showImage : function(e) {
    var id = e.currentTarget.id;
    if (this.data.imageList.length > 0 && this.data.imageList[id] != '') {
      var urls = [];

      for (var i = 0; i < this.data.imageList.length; i++) {
        urls[i] = app.globalData.staticApiUrl + this.data.imageList[i];
      }

      var currentImageUrl = app.globalData.staticApiUrl + this.data.imageList[id];
      wx.previewImage({
        current: currentImageUrl,   // 当前显示图片的http链接
        urls: urls                  // 需要预览的图片http链接列表
      });
    }
  }
  /**
   * 查看子订单图片
   */
  ,showParticipantImage : function(e) {
    var id = e.currentTarget.dataset.id;
    var key = e.currentTarget.dataset.key; 
    var arr = this.data.orderInfo.sub_order;

    if (arr.length > 0 && arr[id].image_list.length > 0) {
      var urls = [];

      for (var i = 0; i < arr[id].image_list.length; i++) {
        urls[i] = app.globalData.staticApiUrl + arr[id].image_list[i];
      }

      var currentImageUrl = app.globalData.staticApiUrl + key;

      wx.previewImage({
        current: currentImageUrl,   // 当前显示图片的http链接
        urls: urls                  // 需要预览的图片http链接列表
      });
    }
  }
  /**
   * 显示单张图片
   */
  ,showSingleImage :function(e) {
    var urls= [];
    urls.push(e.currentTarget.dataset.key);

    wx.previewImage({
      current: e.currentTarget.dataset.key, // 当前显示图片的http链接
      urls: urls // 需要预览的图片http链接列表
    });
  }
  /**
 * 提示
 */
  ,tip: function (msg, status = 'success') {
    wx.showToast({
      title: msg,
      icon: status,
      duration: 1000
    });
  }

  /**
  * 录制mp3音频
  */
  , startRecordMp3: function () {
    app.data.recorderManager.start({
      format: 'mp3'
    });
  }
  /**
   * 停止录音
   */
  , stopRecord: function () {
    app.data.recorderManager.stop();
  }
  /**
   * 播放录音
   */
  ,playRecord: function (e) {

    var that = this;
    var key = e.currentTarget.dataset.key;
    var id = e.currentTarget.dataset.id;

    if (id == 1) {
      var description_voice = key;
    } else {
      var description_voice = app.globalData.staticVoiceUrl  + key;
    }
    
    if (description_voice == '') {
      app.tip("请先录音！")
      return;
    }

    app.data.innerAudioContext.src = description_voice;
    app.data.innerAudioContext.play();

    this.setData({
      toPlay: key,
      isPlay: true
    });
  }  
  /**
   * 暂停播放
   */
  , stopPlayRecord: function() {
    
    app.data.innerAudioContext.stop();

    this.setData({
      toPlay: '',
      isPlay: false
    });
  }
  /**
  * 删除录音
  */
  , deleteRecord: function (e) {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确定删除录音吗？',
      success: function (res) {
        if (res.confirm) {
          that.data.description_voice = '';
          that.setData({
            description_voice: ''
          });
        }
      }
    });
  }
  /**
   * 切换留言方式
   */
  ,changeSendMethod: function (e) {
    app.checkAuthRecord();

    var change_image = app.globalData.imagePath + "/send_image.png";
    var change_character = app.globalData.imagePath + "/send_character.png";
    var change_voice = app.globalData.imagePath + "/send_voice.png";
    var send_image = change_character;

    var change_send_type = 1;
    if (this.data.send_type == 1) {
      send_image = change_voice;
      change_send_type = 2;
    } else if (this.data.send_type == 2) {
      send_image = change_image;
      change_send_type = 3;
    }

    this.setData({
      send_image: send_image,
      send_type: change_send_type
    });
  }
  /**
   * 拼单描述确认字数
   */
  , descConfirm: function (e) {
    var desc_length = 60;
    var desc = e.detail.value;
    if (desc.length > desc_length) {
      desc = desc.substring(0, desc_length);
      this.setData({
        description: desc,
      });
    }
    this.setData({
      desc_count: desc.length,
      description: e.detail.value
    });
  }

  /**
   * 公开/私密留言开关
   */
  , isOpen : function(e) {
      this.setData({
        select_to_user: e.detail.value
      });

    this.data.is_open = e.detail.value;
  }

  /**
   * 图片上传
   * */
  ,uploadImage: function () {
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: res => {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        this.setData({
          upload_images: tempFilePaths
        });
      }
    })
  }
  /**
   * 删除图片
   */
  ,deleteImage : function() {

    var that = this;
    wx.showModal({
      title: '提示',
      content: '确定删除吗？',
      success: function (res) {
        if (res.confirm) {
          that.setData({
            upload_images : []
          });
        }
      }
    });
  }
  /**
   * 打开留言
   */
  , openNote : function() {
    if (this.data.toNote == false) {
      this.setData({
        toNote : true
      });
    }
  }
  /**
   * 私密发送选择的用户ID
   */
  , checkboxChange: function(e) {
    this.data.send_user = e.detail.value;
  }
  /**
   * 提交留言
   */
  ,submitNote : function(e) {
   
    var that = this;
    var order_id = this.data.orderInfo.order_id;
    var send_type = this.data.send_type;
    var description = this.data.description
    var description_voice = this.data.description_voice;
    var upload_images = this.data.upload_images;
    var is_open = this.data.is_open;
    var send_user = this.data.send_user;
    var formId = e.detail.formId;

    // 判断描述不能为空
    if ('' == description && '' == description_voice && upload_images.length <= 0) {
      this.showMessage('留言内容不能为空！');
      return false;
    }

    if (send_type == 1 && '' == description) {
      this.showMessage('发送的文字留言不能为空！');
      return false;
    }

    if (send_type == 2 && '' == description_voice) {
      this.showMessage('发送的语音留言不能为空！');
      return false;
    }

    if (send_type == 3 && upload_images.length <= 0) {
      this.showMessage('发送的图片不能为空！');
      return false;
    }

    wx.showToast({
      icon: "loading",
      title: "正在上传"
    });

    // 文字留言
    if (send_type == 1) {
      this.submiteMessage(e);
    } else {
      this.submitImageVoice(e);
    }
  }
  /**
   * 展示信息
   */
  , showMessage(message, icon = 'none') {
    wx.showToast({
      title: message,
      icon: icon,
      duration: 1500
    });
    return false;
  }

  /**
   * 提交文字留言
   */
  , submiteMessage(e) {
    var that = this;
    var order_id = this.data.orderInfo.order_id;
    var send_type = this.data.send_type;
    var description = this.data.description
    var description_voice = this.data.description_voice;
    var upload_images = this.data.upload_images;
    var is_open = this.data.is_open;
    var send_user = this.data.send_user;
    var formId = e.detail.formId;

    const requestTask = wx.request({
      url: app.globalData.apiUrl + 'message/addMessage',
      method: 'POST',
      data: {
        order_id: order_id,
        send_type: send_type,
        description_voice: that.data.description_voice,
        upload_images: that.data.upload_images,
        description: that.data.description,
        is_open: is_open,
        send_user: send_user,
        form_id: formId
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Cookie": "PHPSESSID=" + wx.getStorageSync('sessionID')
      },
      success: function (res) {
        wx.showToast({
          title: '提交成功！',
          icon: 'success',
          duration: 2000,
          complete: function () {
            that.onPullDownRefresh();
            that.setData({
              description: '',
              desc_count: 0,
              description_voice: '',
              upload_images: []
            });
          }
        });
      },
      fail : function(res) {
        wx.showModal({
          title: '提示',
          content: '提交失败，请重试',
          showCancel: false
        });

        app.reportError(res.errMsg, 'detail-submiteMessage-message/addMessage');
      }
    });
  }
  /**
   * 上传录音或图片
   */
  , submitImageVoice(e) {

    var that = this;
    var order_id = encodeURI(this.data.orderInfo.order_id);
    var send_type = encodeURI(this.data.send_type);
    var description = encodeURI(this.data.description);
    var description_voice = encodeURI(this.data.description_voice);
    var upload_images = this.data.upload_images;
    var is_open = encodeURI(this.data.is_open);
    var send_user = encodeURI(this.data.send_user);
    var formId = encodeURI(e.detail.formId);

    var message = encodeURI(description_voice);
    if (send_type == 3) {
      var message = encodeURI(upload_images[0]);
    } 
    
    wx.uploadFile({
      url: app.globalData.apiUrl + 'message/addImageVoice', //仅为示例，非真实的接口地址
      header: {
        'content-type': 'multipart/form-data',
        'Cookie': 'PHPSESSID=' + wx.getStorageSync('sessionID')
      },
      filePath: message,
      name: 'file',
      formData: {
        order_id: order_id,
        send_type: send_type,
        description_voice: that.data.description_voice,
        upload_images: that.data.upload_images,
        description: that.data.description,
        is_open: is_open,
        send_user: send_user,
        form_id: formId
      },
      success: function (res) {
        wx.showToast({
          title: '提交成功！',
          icon: 'success',
          duration: 2000,
          complete: function () {
            that.onPullDownRefresh();
            that.setData({
              description: '',
              desc_count : 0,
              description_voice : '',
              upload_images : []
            });
          }
        });
      },
      fail: function (res) {
        content = "录音上传失败，请重试！";
        if (send_type == 3) {
          content = "图片上传失败，请重试！";
        }
        wx.showModal({
          title: '提示',
          content: content,
          showCancel: false,
        });

        app.reportError(res.errMsg, 'detail-submitImageVoice-message/addImageVoice');
      }
    });
  }
  /**
   * 获取留言信息
   */
  , getMessage() {
    var that = this;
    var order_id = that.data.id;

    const requestTask = wx.request({
      url: app.globalData.apiUrl + 'message/getMessage',
      method: 'POST',
      data: {
        order_id: order_id,
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        "Cookie": "PHPSESSID=" + wx.getStorageSync('sessionID')
      },
      success: function (res) {
          if (res.data.code == 10000) {
            that.setData({
              message_list : res.data.message.message,
              user_list : res.data.message.user_list
            });
          }
      },
      fail: function (res) {
        wx.showModal({
          title: '提示',
          content: '留言获取失败，请重试！',
          showCancel: false,
        });
      }
    });
  }
  /**
   * To Home Page
   */
  , toHome: function (e) {
    app.formIdSubmit(e);
    wx.switchTab({
      url: '/pages/index/index',
    });
  }
  /**
   * To My Page
   */
  , toMy: function (e) {
    app.formIdSubmit(e);
    wx.switchTab({
      url: '/pages/center/center',
    });
  }

});




// 录音展示图片动态闪烁
function recordImageflash() {
  var _this = this;
  var i = 1;
  this.timer = setInterval(function () {
    i++;
    i = i % 2;
    var image_patch = "";
    if (i == 0) {
      image_patch = app.globalData.imagePath + "/luyin_point.png";
    }
    _this.setData({
      recording_image: image_patch,
    })
  }, 600);
}

//麦克风帧动画
function speaking() {
  var _this = this;
  //话筒帧动画
  var i = 1;
  this.timer = setInterval(function () {
    i++;
    i = i % 5;
    _this.setData({
      j: i
    })
  }, 200);
}

var t = Date.now();
function sleep(d) {
  while (Date.now - t <= d);
}
